package com.sunshine.lnuplus.internet

import com.sunshine.lnuplus.callback.LoadDataCallBack
import com.sunshine.lnuplus.service.LoadBackgroundService
import com.sunshine.lnuplus.utils.BackgroundUtils
import okhttp3.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException

class LoadBackground(
    private val service: LoadBackgroundService,
    private val callBack: LoadDataCallBack) {

    init {
        loadBackgroundUrl()
    }
    /**
     * 下载背景图网址
     */
    private fun loadBackgroundUrl() {
        val url = "http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(url).build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                service.stopSelf()
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                loadBackground(ResolveBackgroundUrl(response.body!!.string()))
            }
        })
    }

    /**
     * 下载背景图
     * @param url
     */
    private fun loadBackground(url: String?) {
        val okHttpClient = OkHttpClient()
        val request = Request.Builder()
            .url(url!!)
            .build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                service.stopSelf()
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                BackgroundUtils.backgroundToFile(service, response, object :
                    LoadDataCallBack {
                    override fun onSuccess() {
                        callBack.onSuccess()
                        service.stopSelf()
                    }
                })
            }
        })
    }

    //解析background的json信息
    private fun ResolveBackgroundUrl(Url: String): String? {
        var backgroundUrl: String? = null
        val url = "http://cn.bing.com"
        try {
            var jsonObject = JSONObject(Url)
            backgroundUrl = jsonObject.getString("images")
            backgroundUrl = backgroundUrl.replace("[", "").replace("]", "").replace(",\"hs\":", "")
            jsonObject = JSONObject(backgroundUrl)
            backgroundUrl = url + jsonObject.getString("url")
        } catch (e: JSONException) {
            e.printStackTrace()
        } finally {
            return backgroundUrl
        }
    }
}